package addTwoNumbers2;

public class AddTwoNumbers {
    public static void main(String[] args) {
        AddTwoNumbers addTwoNumbers = new AddTwoNumbers();
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;

        ListNode n1 = new ListNode(5);
        ListNode n2 = new ListNode(6);
        ListNode n3 = new ListNode(4);
        n1.next = n2;
        n2.next = n3;


        ListNode listNode = addTwoNumbers.addTwoNumbers(l1, n1);

        System.out.println(listNode);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur = new ListNode(0);
        //用来判断上一个加操作有没有>=10，只有0(否)和1(是)两种状态
        int addOne = 0;
        ListNode re = cur;
        while (l1 != null || l2!= null){
            //记录当前加和节点的值
            int temp = 0;
            if (l1 != null) {
                temp += l1.val;
                //指针后移
                l1 = l1.next;
            }
            if (l2 != null) {
                temp += l2.val;
                l2 = l2.next;
            }
            temp += addOne;

            addOne = 0;
            if (temp>=10) {
                //需要进位
                temp = temp-10;
                addOne = 1;
            }
            //处理好的值添加为要返回的下一个节点
            cur.next = new ListNode(temp);
            //指针后移
            cur = cur.next;

        }

        //处理最后如果有进位值，也就是addOne=1.则需要把当前节点后追加一个值1的节点
        if (addOne ==1) {
            cur.next = new ListNode(addOne);
        }
        return re.next;
    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}